﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;


namespace Defector
{
    /*
     * Compose window is a popup called by MainWindow.xaml.cs that allows a user to send a 
     * message to another user.  A combobox displays the users of the system for the sender 
     * to select his recipient.  Text boxes allow input of the subject and content of the message.
     */

    public partial class Compose : Window
    {
        SqlConnection con;
        DataSet namesDataSet = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter();
        string firstName;
        string lastName;

        public Compose(string firstName, string lastName)
        {
            /*
             * firstName and lastName variable are concatenated and sent along with the message
             * as the sender name data.
             */

            this.firstName = firstName;
            this.lastName = lastName;
            InitializeComponent();
        }


        public void setCon(SqlConnection con)
        {
            /*
             * setting the connection for the queries
             */
            
            this.con = con;
        }

        public void setData()
        {            
            try
            {
                /*
                 * Open the connection to populate the combobox of available users.
                 */
                con.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT (First_Name+\' \'+Last_Name) AS Name, Id AS Id FROM People WHERE (Id > 1) ORDER BY Last_Name";
                adapter.SelectCommand = cmd;
                adapter.Fill(namesDataSet, "People");

                DataRow nRow = namesDataSet.Tables["People"].NewRow();

                //Binding the data to the combobox.
                cmbMailTo.DataContext = namesDataSet.Tables["People"].DefaultView;

                //To display category name
                cmbMailTo.DisplayMemberPath =
                   namesDataSet.Tables["People"].Columns["Name"].ToString();
                //To store the ID as hidden
                cmbMailTo.SelectedValuePath =
                   namesDataSet.Tables["People"].Columns["Id"].ToString();
                con.Close();
            }
            catch (Exception ex)
            {
               /*
                * In case of error, do not display the window.
                */
                MessageBox.Show("An error occurred while loading address data.  Please try again.");
                this.Close();
                return;
            }

            /*
             * If the combobox is able to be populated, show the window.
             */
            this.Show();
        }

        
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            /*
             * clicking the close button closes the window.
             */
            this.Close();
        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            /*
             * When the send button is pressed, check to make sure a recipient
             * has been selected from the combobox.
             */
            if(cmbMailTo.SelectedIndex < 0)
            {
                MessageBox.Show("Please select a recipient for your message.");
                return;
            }

            /*
             * Set the personId equal to the value of the selected combobox 
             * item, which is stored in the hidden field.
             */
            int personId = (int)cmbMailTo.SelectedValue;

            /*
             * check to make sure a subject has been entered
             */
            if(String.IsNullOrEmpty(txtComposeSubject.Text.Trim()))
            {
                MessageBox.Show("Please enter a subject for your message.");
                return;
            }

            /*
             * store the subject in a string
             */
            string subject = txtComposeSubject.Text.Trim();

            /*
             * check to make sure a message has been entered
             */
            if(String.IsNullOrEmpty(txtMessage.Text.Trim()))
            {
                MessageBox.Show("Please enter a message to be sent.");
                return;
            }
            
            /*
             * store the message in a string
             */
            string content = txtMessage.Text.Trim();

            /*
             * store the user's own first and last name as one string for use as the
             * sender data for the message.
             */
            string myName = firstName + " " + lastName;

            /*
             * Generate parameterized SQL query to insert the message into the database.
             */
            string query = "INSERT INTO Messages (Subject, Content, Sender, PersonId) VALUES (@Subject , @Content, @Sender, @PersonId)";

            try
            {
                /*
                 * Open the connection and perform the query with the specified string parameters.
                 */
                con.Open();
                SqlCommand cmd = new SqlCommand(query, con);
                cmd.Parameters.AddWithValue("@Subject", subject);
                cmd.Parameters.AddWithValue("@Content", content);
                cmd.Parameters.AddWithValue("@Sender", myName);
                cmd.Parameters.AddWithValue("@PersonId", personId);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                cmd = null;
            }
            catch (Exception ex)
            {
                /*
                 * In case of an error, show a messagebox and do not send.
                 */
                MessageBox.Show("There was an error sending your message.  Please try again.");
                return;
            }
            finally
            {
               /*
                * close the connection
                */
                con.Close();
            }

            /*
             *close the window 
             */
            this.Close();

        }
    }
}
